#require 'digest/sha1'

class User < ActiveRecord::Base
  validates_presence_of     :account, :user_type #:password
  validates_uniqueness_of   :account
 
  attr_accessor :password_confirmation
#  validates_confirmation_of :password
  
  attr_accessor :newpassword,:newpassword_confirmation
  
  def self.change_password(account,usertype,password,newpassword)
    user=self.authenticate(account,password,usertype)
    if user 
      user.password = newpassword
    else 
      user=nil      
    end 
    user
  end
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  def self.authenticate(account, password, usertype)
    user = self.find_by_account(account)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password or user.user_type != usertype
        user = nil
      end
    end
    user
  end
  # 'password' is a virtual attribute
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def after_destroy
    if User.count.zero?
      raise "Can't delete last user"
    end
  end     
  
  private  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
end
